<?php
namespace app\api\controller;

use think\facade\Request;
use think\Controller;
use think\Db;

//无需验证token
class Auth extends Controller
{
    /**
     * 获取Token
     * @return false|string
     * 2001参数错误，2002数据操作错误
     */
    public function access_token()
    {
        // $file_new_name = date('YmdHis').substr(time(), 0, 6).rand(1000,9000);
        // dump(substr(time(),-6));die;
        // dump(md5(uniqid(md5(microtime(true)),true)));die;
        $request = Request::instance();
        $client_id = $request->post("client_id");
        $auth_code = $request->post("auth_code");
        if($client_id == "" || $auth_code == "" ){
            return return_json(2001,"缺少参数client_id或auth_code", '');
        }

        $userInfo = Db::name("user")->field('uid,password')->where(array("username"=>$client_id,'status'=>1))->find();
        if( !$userInfo ){
            return return_json(2001,"参数client_id不存在！", '');
        }
        if($userInfo['password'] == $auth_code){
            $user_id = $userInfo['uid'];
            $user_token = Db::name("user_token")->where(array('user_id'=>$user_id))->find();
            if( $user_token ){
                $expire_time = time()+604800;
                $token = self::settoken();
                $res = Db::name("user_token")->where(array('user_id'=>$user_id))->update(['expire_time'=>$expire_time,'token'=>$token]);
                if($res){
                    //$return_data['user_id'] = $user_id;
                    $return_data['token'] = $token;
                    return return_json(200,"验证成功", $return_data);
                }else{
                    return return_json(2002,"访问出错！", '');
                }
            }else{  //如果是第一次登录创建token
                $data['user_id'] = $user_id;
                $data['token'] = self::settoken();
                $data['expire_time'] = strtotime("+7 days");
                $data['create_time'] = time();
                $id = Db::name("user_token")->insertGetId($data);
                if($id){
                    $return_data['user_id'] = $user_id;
                    $return_data['token'] = $data['token'];
                    return return_json(200,"验证成功", $return_data);
                }else{
                    return return_json(2002,"访问出错！", '');
                }
            }
        }else{
            return return_json(2001,"参数auth_code错误", '');
        }
    }

    /**
     * 生成token
     * @return string
     */
    public function settoken(){
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }
}
